package com.example.db

import android.content.Context
import androidx.room.AutoMigration
import androidx.room.Room
import androidx.room.migration.AutoMigrationSpec
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.db.migrations.UserInfoColumnDelete
import com.example.db.migrations.UserInfoColumnName

/**
 * Room数据工具类
 */
object RoomDBUtils {
    private const val parkDataBaseName = "smart_park.db"
    private lateinit var roomDB:AppDataBase

    private val MIGRATION_2_3 = object : Migration(2,3){
        override fun migrate(database: SupportSQLiteDatabase) {
           try {
               //使用SQL语句来升级数据库
               val reNameTableSQL = "ALTER TABLE user_table RENAME user_info"
               database.execSQL(reNameTableSQL)
           }catch (e:Exception){
               e.printStackTrace()
           }
        }
    }
    //自动升级策略
    private val AUTO_MIGRATION_SPEC = object : AutoMigrationSpec{
        override fun onPostMigrate(db: SupportSQLiteDatabase) {
            super.onPostMigrate(db)
            try {
                //使用SQL语句来升级数据库
                val reNameTableSQL = "ALTER TABLE user_table RENAME user_info"
                db.execSQL(reNameTableSQL)
            }catch (e:Exception){
                e.printStackTrace()
            }
        }
    }
    /**
     * 初始化
     */
    fun initRoom(ctx:Context){
        Room.databaseBuilder(ctx,AppDataBase::class.java, parkDataBaseName)
            //.addMigrations(MIGRATION_2_3)
            //.addAutoMigrationSpec(AUTO_MIGRATION_SPEC)
            .build()
    }

}